<?php
namespace app\publics\controller\api;
use app\ApiController;
use app\member\model\AccountModel;
use linggong\Linggong;
use Qcloud\Cos\Api;
use app\member\model\UsersModel;
use think\Db;

/*------------------------------------------------------ */
//-- 公共调用
/*------------------------------------------------------ */
class Index extends ApiController
{

    public function getParentsByUserId($userId, &$users = [])
    {
        $userInfo = (new UsersModel())->info($userId);
        if (empty($userInfo)) {
            return $users;
        }
        $users[] = $userInfo;

        if ($userInfo['pid'] == 0) {
            array_shift($users); //去除本身数据
            return $users;
        }
        return $this->getParentsByUserId($userInfo['pid'], $users);
    }
    public function getTeamLevelCounts($user_id,$return_arr){
        $child_list = Db::name('users')->where(['pid' => $user_id,'role_id' => 1])->order('up_agent_time asc')->select();
        if($child_list){
            foreach ($child_list as $val){
                $return_arr[] = ['user_id' => $val['user_id'],'level' => $val['level'],'pid' => $val['pid'],'up_agent_time' => $val['up_agent_time']];
                $return_arr =  self::getTeamLevelCounts($val['user_id'],$return_arr);
            }
        }
        return $return_arr;
    }
    public function getUserLdSpread($uid)
    {
        $user = Db::table("users")->where('user_id',$uid)->find();

        if($user['pid']){
            //上级
            $boss = $this->getBossUid($user['pid'],$uid);

            $boss_user = Db::table("users")->where('user_id',$boss['boss_id'])->find();
//dump($boss);exit;
            if($boss['boss_id']){
//                $agent_list = [];
//                $hl = Db::name('users')->where('user_id',$boss['boss_id'])->value('hl_ids');
//                if($hl){
//                    $hl = Db::table("users")->whereIn('user_id', $hl)->select();
//                }else{
//                    $hl = [];
//                }
//                if(count($hl) < 2){
//                    $agent_list = Db::table("users")->where('pid', $boss['boss_id'])->where('up_agent_time','<>','')->whereIn('identity',[1,2])->limit(2)
//                        ->order('up_agent_time asc')->select();
//                }
                $agent_list = Db::table("users")->where('pid', $boss['boss_id'])->where('up_agent_time','<>','')->whereIn('identity',[1,2])->limit(2)
                    ->order('up_agent_time asc')->select();
//                dump($agent_list);exit;
//                $agent_list = array_merge($agent_list,$hl);
                if(count($agent_list) >= 2){
                    $agent_ids = [];
                    foreach ($agent_list as $value){
                        $agent_ids[] = $value['user_id'];
                    }
//                    dump($agent_ids);exit;
                    if(in_array($boss['ouid'],$agent_ids)){

                        if($boss_user['pid']){
                            return $this->getUserLdSpread($boss_user['user_id']);
//                            $jd = $this->getBossUid($boss_user['pid'],$boss['boss_id']);
                            return $jd['boss_id'];
                        }else{
                            return 0;
                        }
                    }else{

                        $agent_list = Db::table("users")->where('pid', $boss_user['user_id'])->where('up_agent_time','<>','')->whereIn('identity',[1,2])->limit(2)
                            ->order('up_agent_time asc')->select();
                        $agent_ids = [];
                        foreach ($agent_list as $value){
                            $agent_ids[] = $value['user_id'];
                        }

                        if(in_array($user['pid'],$agent_ids)){
                            return $this->getUserLdSpread($boss_user['user_id']);
                        }else{
                            return $boss['boss_id'];
                        }

                    }
                }else{

                    return $this->getUserLdSpread($boss_user['user_id']);
                }

            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    public function getBossUid($uid,$ouid)
    {
        $user = Db::table("users")->where('user_id',$uid)->find();
        if($user['identity'] == 2){
            return ['boss_id' => $uid,'ouid' => $ouid];
        }else{
            if($user['pid']){
                return self::getBossUid($user['pid'],$uid);
            }else{
                return ['boss_id' => 0,'ouid' => $ouid];
            }
        }
    }
    public function test()
    {
//        $a = $this->getUserLdSpread(31127);
//        dump($a);
//        exit;
        $DividendModel = new \app\distribution\model\DividendModel();
        $orderInfo  =Db::name('shop_order_info')->where('order_sn','2025052015303')->find();
        $res = $DividendModel->_eval($orderInfo, 'pay', 0);
//        $res = $DividendModel->evalLevelUp($orderInfo);

        die;
        $user_id = 31133;
        $parent_id = Db::name('users')->where(['user_id' => $user_id])->value('pid');
        if($parent_id){
            $agent_list = [];
            //上级直推，小于当前用户ID
            $hl = Db::name('users')->where('user_id',$parent_id)->value('hl_ids');
            if($hl){
                $hl = explode(',',$hl);
            }else{
                $hl = [];
            }

            if(count($hl) < 2) {
                $agent_list = Db::table("users")
                    ->where('pid', $parent_id)
                    ->where('user_id', '<>', $user_id)
                    ->where('up_agent_time', '>', 0)
                    ->whereIn('identity', [1, 2])
                    ->limit(2)
                    ->order('up_agent_time asc')->column('user_id');
            }
            $agent_list = array_merge($agent_list,$hl);
            $no_ids = $agent_list;
            $no_ids[] = $user_id;
            dump($no_ids);
            $hl_user_id = Db::table("users")
                ->where('old_pid', $parent_id)
                ->where('user_id','<', $user_id)
                ->whereNotIn('user_id',$no_ids)
                ->whereIn('identity',[1,0])
                ->column('user_id');
            dump($hl_user_id);
        }
        exit;

        $data = [
            "msgId"=>time(),
            "requestTimestamp"=>date("Y-m-d H:i:s",time()),
            "merOrderId"=>"327M20220414172448".time(),
            "srcReserve"=>"webpay",
            "mid"=>"898201612345678",
            "tid"=>"88880001",
            "instMid"=>"YUEDANDEFAULT",
            "attachedData"=>"336000_0003",
            "totalAmount"=>1,
            "tradeType"=>"JSAPI",
            "subOpenId" => 'o8B1n6lBoWtK7c-1w22DkmT2A4dE'
        ];
        $client = new \payment\unionPay\unionPay();
        $res = $client->unifiedOrder($data);
        dump($res);
        exit;
        $url = "https://test-api-open.chinaums.com/v1/netpay/webpay/pay";

        $data = '{"msgId":"001","requestTimestamp":"2024-05-08 11:15:21","merOrderId":"327M202204141724489725391331","srcReserve":"webpay","mid":"898201612345678","tid":"88880001","instMid":"YUEDANDEFAULT","goods":[{}],"subOrders":[{}],"attachedData":"336000_0003","totalAmount":1,"retCommParams":{},"disablePayChnl":"balance-余额 moneyFund-余额宝 debitCardExpress-借记卡快捷 creditCard-信用卡 pcredit-花呗 pcreditpayInstallment-花呗分期 coupon-红包 point-积分 promotion-优惠（包含实时优惠+商户优惠） voucher-营销券 mdiscount-商户优惠"}';
        $client = new \DefaultOpenApiClient();
        $content = $client->executeGet($appid,$appkey,$url,$data);
        $obj = json_decode($content);
        print_r($obj->errCode);
        print_r($obj->errInfo);
        exit;

        $buyUserParents = $this->getParentsByUserId(30471);
        $userinfos = (new UsersModel())->info(30471);
        array_unshift($buyUserParents,$userinfos);
        dump($buyUserParents);exit;

        exit;
        $video_path = $_SERVER['DOCUMENT_ROOT'].'/upload/snap_file/';
        $cover_path = 'bDAtqcnOrHSqqjeg.mp4';

        $a = getVideoCover($video_path,$cover_path);
        dump($a);
        exit;
        $path = '/upload/image/2024/04/661c99f802fe0.jpg';
        $path_arr = explode('/',$path);
        $path_arr[count($path_arr) - 1] = 'share_'.$path_arr[count($path_arr)-1];
        $new_path = implode('/',$path_arr);
        dump($new_path);
        exit;
        $path = $_SERVER['DOCUMENT_ROOT'].'/upload/image/2024/04/661c99f802fe0.jpg';
        $image = \think\Image::open($path);
        $image->water($_SERVER['DOCUMENT_ROOT'].'/static/images/play.png',\think\Image::WATER_CENTER)->save($path);
//        $image->thumb(150,150,\think\Image::THUMB_CENTER)->save($path);
        dump($image);exit;
//        $profit_pid = $this->getProfit(30475,30476);
//        dump($profit_pid);
        exit;

        $order_id =205;
        $userModel = new UsersModel();
        $order = \app\shop\model\OrderModel::where("order_id", $order_id)->find();
        $result =$userModel->addLdGrade($order);
        //dump($result);
        //2024010227026
    }
    /**
     * 获取所属上级 getProfit
     * @param int $pid [上级id]
     * @return void
     */
    public function getProfit($pid = 0,$org_user_id = 0)
    {
        $profituser = Db::table("users")->where('user_id', $pid)->field('role_id,profit_pid,user_id,identity')->find();
        if ($profituser['identity'] <= 1) {
            if ($profituser['profit_pid'] == 0) {
                return 0;
            }
            return $this->getProfit($profituser['profit_pid'],$org_user_id);
        }
        if($profituser['user_id']){
            $ot_user = Db::name('users')->where(['pid' => $profituser['user_id']])->order('user_id asc')->limit(2)->column('user_id');
            if(in_array($org_user_id,$ot_user) && $profituser['profit_pid'] > 0){
                return $this->getProfit($profituser['profit_pid'],$org_user_id);
            }else{
                return $profituser['user_id'];
            }
        }

        return $profituser['user_id'];
    }
    /*------------------------------------------------------ */
    //-- 获取默认设置
    /*------------------------------------------------------ */
    public function defaultSetting(){
        $rows = (new \app\mainadmin\model\SettingsModel)->where('is_open',1)->select();
        $web_path = config('config.host_path');
        foreach ($rows as $row){
            $row['data'] = htmlspecialchars_decode($row['data']);
            $row['data'] = preg_replace('/<img src=\"\/upload/', '<img src="'.$web_path.'/upload',$row['data']);
            $row['data'] = preg_replace('/<img/', '<img style="width:100%"',$row['data']);
            $setting[$row['name']] = isJson($row['data']);
        }
        if (empty($setting['sms_fun']) == false){
            $setting['sms_public_register'] = $setting['sms_fun']['register'];
            $setting['sms_public_login'] = $setting['sms_fun']['login'];
            $setting['sms_public_forget_password'] = $setting['sms_fun']['forget_password'];
            $setting['sms_public_edit_pay_pwd'] = $setting['sms_fun']['edit_pay_pwd'];
            $setting['sms_public_bind_mobile'] = $setting['sms_fun']['bind_mobile'];
            unset($setting['sms_fun']);
        }
        $setting['withdraw_type'] = explode(',',$setting['withdraw_type']);
        $data['setting'] = $setting;
        session_start();
        $data['session_id'] = session_id();

        //设置地方释放扶持金
        $DividendInfo = settings('DividendInfo');
        $DividendSatus = settings('DividendSatus');
        $userModel = new \app\member\model\UsersModel();
        //根据注册时间最早的时间查3个下级用户
        $start_push_User = $userModel->where([
            ['pid', '=', $this->userInfo['user_id']],
        ])->select();


        $start_push_Usercount = $userModel->where([
            ['pid', '=', $this->userInfo['user_id']],
        ])->count();


        $manzugxIds = '';
        if ($start_push_Usercount > 0) {
            foreach ($start_push_User as $user){
                $manzugxIds .= $user['user_id'] . ',';
            }
            $pull_UserList = rtrim($manzugxIds,',');
        }else{
            $pull_UserList = '30000';
        }


        $rebate_push_num = 0;
        $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => $this->userInfo['user_id']])
            ->where('role_id','in',[1,2])->order('up_agent_time asc')->limit($DividendInfo['rebate_push_num'])->select();
        if(count($ot_user) >= $DividendInfo['rebate_push_num']){
            foreach ($ot_user as $ot){
                if($ot['role_id'] == 2){
                    $rebate_push_num++;
                }
            }
        }
        /*
        $rebate_push_num = $userModel
            ->where([
                ['pid', '=', $this->userInfo['user_id']],
                ['role_id', '=', 2],
//                ['profit_pid', '<>', $userInfo['user_id']],
            ])
            ->count();
        */

        $AccountModels = new \app\member\model\AccountModel();
        if($DividendSatus == 1){
            if ($rebate_push_num >= $DividendInfo['rebate_push_num']) {
                $AccountModels->releaseSupport($this->userInfo['user_id']);
            }
            if($this->userInfo['isrelease'] == 1){
                $AccountModels->releaseSupport($this->userInfo['user_id']);
            }
        }
        //设置地方释放扶持金


        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 验证码
    /*------------------------------------------------------ */
    public function verify(){
        $session_id = input('session_id','','trim');
        $config =    [
            'fontSize' => 30,// 验证码字体大小
            'length'   => 4,// 验证码位数
            'useNoise' => false,// 关闭验证码杂点
            'codeSet' => '0123456789'
        ];
        $Captcha = new \lib\Captcha($config);
        return $Captcha->entry($session_id);
    }
    /*------------------------------------------------------ */
    //-- 生成自定义随机字符串
    /*------------------------------------------------------ */
    public function getRandstr(){
        $length = input('length',10,'intval');
        $data['str'] = random_str($length);
        return $this->success($data);
    }

    public function upVideo()
    {
        if($_FILES['file']['size'] > 31457280){
            return $this->error('最大支持 30M MB上传.');
        }
        if (strstr($_FILES["file"]['type'],'video/mp4') == false) {
            return $this->error('未能识别文件格式，请核实.');
        }
        $file_type = end(explode('.',$_FILES['file']['name']));
        if (in_array($file_type,['mp4']) == false){
            return $this->error('格式不对，只支持 (apk格式)，请核实.');
        }
        $dir = config('config._upload_').'snap_file/';
        makeDir($dir);
        $file_name = random_str(16).'.'.$file_type;
        move_uploaded_file($_FILES['file']['tmp_name'],$dir.$file_name);
        $data['filename'] = trim($dir.$file_name,'.');
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 公共上传临时图片
    /*------------------------------------------------------ */
    public function upImage(){
        $file = $_FILES['file']['name'];
        $type = input('type','','trim');
        $width = input('width',300);
        $extend = getFileExtend($file);
        if (in_array($extend[1],['jpg','png']) == false){
            return $this->error('只允许上传jpg、png格式图片.');
        }
        $file_path = config('config._upload_').'snap_file/'.date('m').'/';
        if(!file_exists($file_path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            makeDir($file_path);
        }
        $file = $file_path.random_str(15).rand(10,99).'.'.$extend[1];

        $res = move_uploaded_file($_FILES['file']['tmp_name'], $file) ;

        if($res == false) {
            return $this->error('上传文件失败.');
        }
        $file = createThumbnail($file,$file,$width);
        $data['file'] = trim($file,'.');
        $data['type'] = $type;
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 删除上传的临时图片
    /*------------------------------------------------------ */
    public function removeImage(){
        $this->checkLogin();//验证登陆
        $file = input('file','','trim');
        if (strstr($file,'snap_file') == false){
            return $this->error('此接口只能用于删除临时图片.');
        }
        @unlink('.'.$file);
        return $this->success();
    }
    /**
     * [addOrder 下单]
     */
    public function addOrder()
    {
        $time = date('Y-m-d H:i:s',time());
        $json = '{
                    "create_time": "'.$time.'",
                    "type": 0,                                
                    "out_order_id": "101",                 
                    "openid": "obz8f4-vknNtePru3j8Mb8qbiO_o",
                    "path": "pages/shop/goods/info?goods_id=101",    
                    "scene": 1177,                        
                    "out_user_id": "29891",
                    "order_detail":
                    {
                        "product_infos":
                        [
                            {
                                "out_product_id": "101",
                                "out_sku_id":"0",
                                "product_cnt": 1,
                                "sale_price": 168,   
                                "path": "pages/shop/goods/info?goods_id=101",
                                "title" : "玫瑰金小蛮腰项链",
                                "head_img": "http://baseshop.l.com/upload/gimg/2021/05/609f2c70e8860.png"
                            }
                        ],
                        "pay_info": {
                            "pay_method": "其他",
                            "prepay_id": "42526234625",
                            "prepay_time": "'.$time.'",
                            "pay_method_type":99
                        },
                        "price_info": {        
                            "order_price": 168,
                            "freight": 0,
                            "discounted_price": 0,
                            "additional_price": 0,
                            "additional_remarks": ""
                        }
                    },
                    "delivery_detail": {
                        "delivery_type": 1
                    },
                    "address_info": {
                        "receiver_name": "毛先生",
                        "detailed_address": "天河区沐陂大街",
                        "tel_number": "16624661113",
                        "country": "中国",
                        "province": "广东",
                        "city": "广东",
                        "town": "天河区"
                    }
                }';
        $data = json_decode($json,true);

        $res = (new  \app\weixin\model\WeiXinMpModel)->addOrder($data);

        print_r($res);
    }


    /**
     * [addOrder 下单]
     */
    public function pay()
    {
        $time = date('Y-m-d H:i:s',time());
        $json = '{
                    "order_id":1884852141765296134,
                    "out_order_id": "1",
                    "openid": "obz8f4-vknNtePru3j8Mb8qbiO_o",
                    "action_type": 1,       
                    "action_remark": "", 
                    "transaction_id": "16624661113",      
                    "pay_time": "'.$time.'"      
                }';
        $data = json_decode($json,true);
        // print_r($data);
        $res = (new  \app\weixin\model\WeiXinMpModel)->pay($data);

        print_r($res);
    }

    /**
     * [addOrder 下单]
     */
    public function sendorder()
    {
        $res = (new  \app\weixin\model\WeixinVideoOrderModel)->getCompanyList();
        print_r($res);
    }
    // 腾讯云存储查询存储桶列表
    public function ossTest()
    {
        // $file = request()->file('upload');
        // print_r($_FILES);
        // 引入类库
        require '../extend/storage/oss/storage.php';
        $storage = new \storage();
        // $res = $storage->createBucket('my-test-mao');
        // $res = $storage->getBucketList();
        // $res = $storage->doesBucketExist('my-test-mao');
        // $res = $storage->getBucketMeta();
        // $res = $storage->getBucketInfo('my-test-mao');

        // $res = $storage->deleteBucket('my-test-mao1');
        // print_r($res);

        // $res = $storage->upload('folder/mao_test3.jpg',$_FILES['upload']);
        // if ($res['code'] == 1) {
        //     echo '<img src="'.$res['url'].'">';
        // }

        // $storage->getObject('O1CN01fdWwBh1yVyhywd4c9_!!3851296585-0-lubanu-s.jpg_430x430q90.jpg');
        // $res = $storage->doesObjectExist('mao_test222.jpg');
        // print_r($res);
        // $res = $storage->getSimplifiedObjectMeta('mao_test2.jpg');
        // print_r($res);
        // $storage->listObjects();
        // $res = $storage->copyObject('test.jpg','test222.jpg');
        // print_r($res);
        // $res = $storage->deleteObject('test222.jpg');
        // print_r($res);
        // $res = $storage->deleteObjects(['mao_test2.jpg','mao_test3.jpg']);
        // print_r($res);
    }

    public function cosTest()
    {
        $StorageModel = new \app\mainadmin\model\StorageModel();
        $row = $StorageModel->getRow(settings('uploadType'));
        require '../extend/storage/'.$row['type'].'/storage.php';
        $storage = new \storage();

        // $res = $storage->createBucket('mytestmao1-1259135872');
        // print_r($res);
        // $res = $storage->getBucketList();
        // $res = $storage->deleteBucket('mytestmao1-1259135872');
        // $res = $storage->listObjects();
        // $res = $storage->upload('folder/mao_test2.jpg',$_FILES['upload']);
        // $res = $storage->copyObject('exampleobject.jpg','exampleobject2.jpg');
        // $res = $storage->deleteObjects(['8a447202105291021335493.png','exampleobject.jpg']);
        // print_r($res);
    }
    public function qiniuTest()
    {
        $StorageModel = new \app\mainadmin\model\StorageModel();
        $row = $StorageModel->getRow(settings('uploadType'));
        require '../extend/storage/'.$row['type'].'/storage.php';
        $storage = new \storage();
        // $res = $storage->createBucket('my-test-mao1');
        // print_r($res);
        // $res = $storage->getBucketList();
        // $res = $storage->deleteBucket('my-test-mao1');
        // $res = $storage->listObjects();
        // print_r($_FILES);
        // $res = $storage->upload('folder/mao_test3.jpg',$_FILES['upload']);
        // $res = $storage->copyObject('FodbUKF-EMc2y_nCY_E0LSlxH_pd',rand(100000,9999999).'.jpg');
        // $res = $storage->deleteObject('FodbUKF-EMc2y_nCY_E0LSlxH_pd');
        $res = $storage->deleteObjects(['7383207.jpg','folder/mao_test2.jpg','test3.jpg','test4.jpg','folder/mao_test3.jpg']);
        print_r($res);
    }
    /*<!DOCTYPE html>
        <html>
        <head>
            <title></title>
        </head>
        <body>
            <h1>hello worlds</h1>
            <form action="/index.php/publics/api.index/qiniuTest" method="post" enctype="multipart/form-data">
                <p><input type="file" name="upload"></p>
                <p><input type="submit" value="submit"></p>
            </form>
        </body>
        </html>*/

    public function getWxShare()
    {
        $url = input('url','','trim');
        $wxShare = (new \app\weixin\model\WeiXinModel)->getSignPackage($url);
        $data['wxShare'] = $wxShare;
        $data['token'] = $this->userInfo['token'];
        return $this->success($data);
    }

    public function editWxInfo()
    {
        $user_id = input('user_id',0);
        $upArr['nick_name'] = input('nickname','','trim');
        $upArr['headimgurl'] = input('avatar','','trim');
        $res = Db::name('users')->where(['user_id' => $user_id])->update($upArr);
        return $this->success('修改成功.');
    }
}
?>
